import hashlib

class TorrentTags:
    fileName = "NAME"
    trackerUrl = "TRACKER"
    size = "SIZE"
    chunkSize = "CHUNK"
    fileHash = "FILEHASH"
    pieceHash = "HASH"

def createTorrent(fileName, trackerUrl, chunkSize, torrentName):
    fileObj = open(fileName, "rb")
    EOL = "\n"
    chunkSizeKb = chunkSize *1024 #Convert to KB
    fileNameTag = TorrentTags.fileName + ":" + fileName + EOL
    trackerUrlTag = TorrentTags.trackerUrl + ":" + trackerUrl + EOL
    piecesHash = []
    preHashTag = TorrentTags.pieceHash
    md5 = hashlib.md5()
    fileSize = 0
    while True:
        data = fileObj.read(chunkSizeKb)
        if not data:
            break
        pieceHash = hashlib.sha1(data).hexdigest()#Tell that you use hexdigest
        pieceHashTag = preHashTag +":" + pieceHash + EOL
        piecesHash.append(pieceHashTag)
        md5.update(data)
        fileSize += len(data)
    fileHash = md5.hexdigest()
    fileHashTag = TorrentTags.fileHash + ":" + fileHash + EOL
    fileSizeTag = TorrentTags.size + ":" + str(fileSize) + EOL
    chunkSizeTag = TorrentTags.chunkSize + ":" + str(chunkSize) + EOL
    
    order = [fileNameTag,trackerUrlTag,fileSizeTag,chunkSizeTag,
             fileHashTag] + piecesHash
    torrentFile = open(torrentName, "w")
    torrentFile.writelines(order)
    torrentFile.close()


if __name__ == '__main__':
    fileName = "Camel - Lawrence.flv"
    torrentName = "Lawrence.tor"
    chunkSize = 512
     
    createTorrent(fileName, "http://boo.com", chunkSize, torrentName)
    